<?php
/**
 * 新浪oauth2.0登录
 * @author nswe
 */
session_start();
class Sina extends OauthBase
{
	function __construct($config)
	{

		$_SESSION['apiKey']=$config['apiKey'];
		$_SESSION['apiSecret']=$config['apiSecret'];
	}

	function getLoginUrl($url='')
	{
		require_once(dirname(__FILE__)."/API/saetv2.ex.class.php");

		$o = new SaeTOAuthV2($_SESSION['apiKey'] , $_SESSION['apiSecret']);
		$code_url = $o->getAuthorizeURL($url?$url:parent::getReturnUrl());

		return $code_url;
	}

	function checkStatus($parms)
	{
		return true;
	}

	function getAccessToken($parms)
	{
		require_once(dirname(__FILE__)."/API/saetv2.ex.class.php");

		$o = new SaeTOAuthV2($_SESSION['apiKey'] , $_SESSION['apiSecret']);
		$token = '';
		if(isset($_REQUEST['code']))
		{
			$keys = array();
			$keys['code'] = $_REQUEST['code'];
			$keys['redirect_uri'] = parent::getReturnUrl();
			try
			{
				$token = $o->getAccessToken('code',$keys) ;
			}
			catch (OAuthException $e)
			{}
		}

		if($token)
		{
			$_SESSION['token']=$token;
			setcookie( 'weibojs', http_build_query($token) );
		}
	}

	function getUserInfo()
	{
		require_once(dirname(__FILE__)."/API/saetv2.ex.class.php");

		$token = ISession::get('token');
		$c = new SaeTClientV2($_SESSION['apiKey'],$_SESSION['apiSecret'],$token['access_token'] );
		$ms  = $c->home_timeline();
		$uid_get = $c->get_uid();
		$uid = $uid_get['uid'];
		$user_message = $c->show_user_by_id($uid);

		$userInfo = array();
		$userInfo['id']   = $uid;
		$userInfo['name'] = isset($user_message['screen_name']) ? $user_message['screen_name'] : '';

		return $userInfo;
	}

	public function getFields()
	{
		return array(
			'apiKey' => array(
				'label' => 'apiKey',
				'type'  => 'string',
			),
			'apiSecret' => array(
				'label' => 'apiSecret',
				'type'  => 'string',
			),
		);
	}
}
